﻿using System;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;
using hamburgerwang.businfo;

namespace SuzhouBus
{
    public partial class FormStopQuery : Form
    {
        private bool m_BusInfoLoaded;
        private bool m_RealTimeLoaded;

        public FormStopQuery()
        {
            InitializeComponent();
        }

        private void buttonStopQuery_Click(object sender, EventArgs e)
        {
            this.buttonStopQuery.Enabled = false;
            Application.DoEvents();
            HtmlDocument busInfoDocument = this.webBrowserBusInfo.Document;
            busInfoDocument.Forms[0].GetElementsByTagName("select")[0].SetAttribute("value", @"线路站点");
            busInfoDocument.Forms[0].GetElementsByTagName("input")[0].SetAttribute("value", this.textBoxStop.Text.Trim());
            busInfoDocument.Forms[0].GetElementsByTagName("input")[1].InvokeMember("click");
            WaitSeconds();
            int retryCount = 0;
            while (this.IsFetchingBusInfoData())
            {
                if (retryCount > 50)
                {
                    break;
                }
            }
            BusLine[] lines = this.GetBusLines();
            this.comboBoxLines.DataSource = lines;


            HtmlDocument realTimeDocument = this.webBrowserRealTime.Document;
            realTimeDocument.GetElementById("ctl00$ContentPlaceHolder$ctl00$ctl00$StandName").SetAttribute("value", this.textBoxStop.Text.Trim());
            realTimeDocument.GetElementById("ctl00$ContentPlaceHolder$ctl00$ctl00$SearchCode").InvokeMember("click");
            WaitSeconds();
            retryCount = 0;
            while (this.IsFetchingRealTimeData())
            {
                if (retryCount > 50)
                {
                    break;
                }
            }
            BusStop[] stops = this.GetBusStops();
            this.comboBoxStops.DataSource = stops;

            this.Refresh();
            this.LoadPage();
        }

        private void webBrowserRealTime_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.m_RealTimeLoaded = true;
            this.SetQueryButtonStatus();
        }

        private void webBrowserBusInfo_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.m_BusInfoLoaded = true;
            this.SetQueryButtonStatus();
        }

        private void SetQueryButtonStatus()
        {
            if (m_BusInfoLoaded && m_RealTimeLoaded)
            {
                this.buttonStopQuery.Enabled = true;
            }
            else
            {
                this.buttonStopQuery.Enabled = false;
            }
        }

        private bool IsFetchingRealTimeData()
        {
            WaitSeconds();
            HtmlElement container  = this.webBrowserRealTime.Document.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_MessageCode");
            if (container.Children.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool IsFetchingRealTimeData2()
        {
            WaitSeconds();
            HtmlElement container = this.webBrowserRealTime.Document.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_Message");
            if (string.IsNullOrEmpty(container.InnerText))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool IsFetchingBusInfoData()
        {
            WaitSeconds();
            if (this.webBrowserBusInfo.Document.Forms[0].Name != "form1")
            {
                return true;
            }
            else if (this.webBrowserBusInfo.Document.Forms[0].Children.Count <= 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private BusStop[] GetBusStops()
        {
            BusStop[] stops;
            HtmlElement container = this.webBrowserRealTime.Document.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_MessageCode");
            if (container.Children.Count > 0)
            {
                HtmlElement tbody = container.Children[1].FirstChild;
                if (tbody.TagName.ToLower() != "tbody")
                {
                    tbody = tbody.Parent;
                }
                stops = new BusStop[tbody.Children.Count - 1];
                for (int i = 1; i < tbody.Children.Count; i++)
                {
                    BusStop stop = new BusStop();
                    HtmlElement element = tbody.Children[i];
                    stop.ID = element.Children[1].InnerText;
                    stop.Name = string.Format("{0} ({1}{2})", element.Children[0].InnerText, element.Children[3].InnerText, element.Children[5].InnerText);
                    stop.Description = element.Children[4].InnerText;
                    stops[i - 1] = stop;
                }
            }
            else
            {
                stops = new BusStop[0];
            }
            return stops;
        }

        private BusLine[] GetBusLines()
        {
            BusLine[] lines;
            HtmlElement container = this.webBrowserBusInfo.Document.Forms[0];
            if (container.Children.Count > 0)
            {
                lines = new BusLine[container.Children.Count];
                for (int i = 0; i < container.Children.Count; i++)
                {
                    BusLine line = new BusLine();
                    HtmlElement tbody = container.Children[i].FirstChild;
                    if (tbody != null)
                    {
                        if (tbody.TagName.ToLower() != "tbody")
                        {
                            tbody = tbody.Parent;
                        }
                        line.No = tbody.Children[2].Children[1].Children[1].InnerText;
                        line.Routine = tbody.Children[6].Children[1].InnerText.Split(new char[]{'、'}, StringSplitOptions.RemoveEmptyEntries);
                        line.Description = tbody.Children[8].Children[1].InnerText + Environment.NewLine;
                        line.Price = 0; // Convert.ToDecimal(tbody.Children[2].Children[1].InnerText);
                    }
                    lines[i] = line;
                }
            }
            else
            {
                lines = new BusLine[0];
            }
            return lines;
        }

        private void comboBoxLines_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxLines.SelectedIndex >= 0)
            {
                BusLine line = (BusLine)this.comboBoxLines.SelectedItem;
            }
        }

        private void WaitSeconds()
        {
            Application.DoEvents();
            Thread.CurrentThread.Join(1000);
        }

        private void FormStopQuery_Load(object sender, EventArgs e)
        {
            this.LoadPage();
        }

        private void LoadPage()
        {
            this.m_BusInfoLoaded = false;
            this.m_RealTimeLoaded = false;
            this.SetQueryButtonStatus();
            this.webBrowserRealTime.Navigate(Program.RealTimeProviderURL);
            this.webBrowserBusInfo.Navigate(Program.BusInfoProviderURL);
            WaitSeconds();
        }

        private void buttonDistance_Click(object sender, EventArgs e)
        {
            if (this.comboBoxLines.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please input a bus number.");
                this.comboBoxLines.Focus();
                return;
            }
            if (this.comboBoxStops.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a bus stop.");
                this.comboBoxStops.Focus();
                return;
            }
            HtmlDocument realTimeDocument = this.webBrowserRealTime.Document;
            realTimeDocument.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_BusLine").SetAttribute("value", this.comboBoxLines.Text);
            realTimeDocument.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_StandCode").SetAttribute("value", this.comboBoxStops.SelectedValue.ToString());
            realTimeDocument.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_Search").InvokeMember("click");
            WaitSeconds();
            int retryCount = 0;
            while (this.IsFetchingRealTimeData2())
            {
                if (retryCount > 50)
                {
                    break;
                }
            }
            this.labelDistance.Text = realTimeDocument.GetElementById("ctl00_ContentPlaceHolder_ctl00_ctl00_Message").InnerText;
        }

    }
}
